<template>
  <div class="chat-container">
    <div v-if="historyList.length === 0" class="empty">
      <u-empty></u-empty>
      <!-- <button type="button" class="empty-button" @click="empty">
				发起一段对话吧
			</button> -->
    </div>
    <!-- <i-modal title="确认删除会话？" :visible="modalVisible" @ok="handleConfirm()" @cancel="handleModalShow">
		</i-modal> -->
    <template v-for="(item, index) in historyList">
      <div class="chat" :key="index"
        @click="checkoutConversation(item, item.tencent_user_id)">
        <div class="avatar-container">
          <image :src="item.avatar || '/static/images/avatar.png'"
            style="width: 113rpx;height: 113rpx;display: block;border-radius: 50%;" />
        </div>
        <div class="right">
          <div class="information">
            <div class="username">{{item.nickname || item.tencent_user_id}}</div>
            <div class="content" >
              通话记录
            </div>
          </div>
          <div class="time">
            <div class="last">{{item.max_end_time}}</div>
            <div class="remain" v-if="item.unreadCount > 0">
              <span v-if="item.unreadCount > 99" class="info">99+</span>
              <span v-else class="info">{{item.unreadCount}}</span>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- <template v-for="item in allConversation">
      <div class="chat" v-if="item.type === 'C2C'" :key="item.conversationID" @longpress="longTimePress(item)"
        @click="checkoutConversation(item, item.userProfile.nick || item.userProfile.userID)">
        <div class="avatar-container">
          <image :src="item.userProfile.avatar || '/static/images/avatar.png'"
            style="width: 113rpx;height: 113rpx;display: block;border-radius: 50%;" />
        </div>
        <div class="right">
          <div class="information">
            <div class="username">{{item.userProfile.nick || item.userProfile.userID}}</div>
            <div class="content" v-if="!item.lastMessage.isRevoked">
              <block v-if="item.lastMessage.messageForShow == '[自定义消息]'">
                {{item.lastMessage | parseMsg}}
              </block>
              <block v-else>
                {{item.lastMessage.messageForShow}}
              </block>
            </div>
            <div class="content" v-else>
              <template v-if="myInfo.userID === item.lastMessage.fromAccount">你撤回了一条消息</template>
              <template v-else>{{item.lastMessage.fromAccount}}撤回了一条消息</template>
            </div>
          </div>
          <div class="time">
            <div class="last">{{item.lastMessage._lastTime}}</div>
            <div class="remain" v-if="item.unreadCount > 0">
              <span v-if="item.unreadCount > 99" class="info">99+</span>
              <span v-else class="info">{{item.unreadCount}}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="chat" v-else-if="item.type === 'GROUP'"
        @click="checkoutConversation(item, item.groupProfile.name || item.groupProfile.ID)" :key="item.conversationID"
        @longpress="longTimePress(item)">
        <div class="avatar-container">
          <image :src="item.groupProfile.avatar"
            style="width: 113rpx;height: 113rpx;display: block;border-radius: 50%;" />
        </div>
        <div class="right">
          <div class="information">
            <div class="username">{{item.groupProfile.name || item.groupProfile.groupID}}</div>
            <div class="content" v-if="!item.lastMessage.isRevoked">
              <template
                v-if="item.lastMessage.fromAccount === '@TIM#SYSTEM'">{{item.lastMessage.messageForShow}}</template>
              <template v-else>{{item.lastMessage.fromAccount}}：{{item.lastMessage.messageForShow}}</template>
            </div>
            <div class="content" v-else>
              <template v-if="myInfo.userID === item.lastMessage.fromAccount">你撤回了一条消息</template>
              <template v-else>{{item.lastMessage.fromAccount}}撤回了一条消息</template>
            </div>
          </div>
          <div class="time">
            <div class="last">{{item.lastMessage._lastTime}}</div>
            <div class="remain" v-if="item.unreadCount > 0">
              <span v-if="item.unreadCount > 99" class="info">99+</span>
              <span v-else class="info">{{item.unreadCount}}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="chat" v-else-if="item.type === '@TIM#SYSTEM'" @click="checkoutNotification(item)"
        :key="item.conversationID" @longpress="longTimePress(item)">
        <div class="avatar-container">
          <image src="/static/images/system.png" class="avatar" />
        </div>
        <div class="right">
          <div class="information">
            <div class="username">系统通知</div>
            <div class="content">点击查看</div>
          </div>
          <div class="time">
            <div class="last"></div>
            <div class="remain" v-if="item.unreadCount > 0">
              <span v-if="item.unreadCount > 99" class="info">99+</span>
              <span v-else class="info">{{item.unreadCount}}</span>
            </div>
          </div>
        </div>
      </div>
    </template> -->
    <u-tabbar :value="value1" inactiveColor='#000' activeColor='#93b262' :customStyle="tabBarStyle" :border='false'>
      <u-tabbar-item text="消息" icon="/static/theme/chat-theme.png"></u-tabbar-item>
      <u-tabbar-item text="账号" icon="/static/theme/own.png" @click="switchTab"></u-tabbar-item>
    </u-tabbar>
  </div>
</template>

<script>
  import {
    mapState,
    mapGetters
  } from 'vuex'
  import {
    checkVersion,
    throttle
  } from '@/utils/index.js'
  export default {
    data() {
      return {
        tabBarStyle: {
          "backgroundColor": "#ededed",
        },
        value1: 0,
        modalVisible: false,
        conversation: {},
        version: '1.0.0',
        historyList: []
      }
    },
    computed: {
      ...mapState({
        allConversation: state => {
          let arr = state.conversation.allConversation
          arr.map(e => {
            try {
              e.lastMessage.payload.data = JSON.parse(e.lastMessage.payload.data)
              try {
                e.lastMessage.payload.data.data = JSON.parse(e.lastMessage.payload.data.data)
              } catch (e) {
                //TODO handle the exception
              }
            } catch (e) {
              //TODO handle the exception
            }
            return e
          })
          return arr
        },
        isSdkReady: state => state.global.isSdkReady
      }),
      unreadCount() {
        let arr = this.allConversation
        let unreadCount = 0
        arr.forEach(e => {
          unreadCount += e.unreadCount
        })
        return unreadCount
      },
      ...mapGetters(['totalUnreadCount', 'myInfo'])
    },
    filters: {
      parseMsg(data) {
        let e = data.payload.data.data
        if (e?.data?.cmd) {
          if (e.data.cmd == "audioCall") {
            return '语音通话'
          } else if (e.data.cmd == "videoCall") {
            return '视频通话'
          } else if (e.data.cmd == "switchToAudio") {
            return '转语音通话'
          } else if (e.data.cmd == "hangup") {
            return '通话结束'
          }
        } else if (e.data) {
          if (e.call_type == 1) {
            return '语音通话'
          } else if (e.call_type == 2) {
            return '视频通话'
          }
        }
        return data.messageForShow
      }
    },
    // 消息列表下拉
    onPullDownRefresh() {
      this.getCallUser()
      // throttle(uni.$app.getConversationList(), 1000)
      // uni.stopPullDownRefresh()
    },

    onShow() {
      // uni.$app.getConversationList()
      this.getCallUser()
    },
    onReady() {
      uni.hideTabBar();
    },
    methods: {
      getCallUser() {
        this.$http.getCallUser().then(res => {
          this.historyList = res.data
          console.log(this.historyList);
          uni.stopPullDownRefresh()
        })
      },
      checkVersion() {
        this.$http.appUpdated().then(res => {
          let info = res.data
          if (checkVersion(this.version, info.version)) {
            if (info.is_force) {
              uni.setStorageSync('update', info)
              this.$redirectTo('/pages/system/update/index')
              return
            }
            uni.showModal({
              title: '提示',
              content: '发现新版本: ' + info.version,
              success: (e) => {
                if (e.confirm) {
                  uni.setStorageSync('update', info)
                  this.$navigateTo('/pages/system/update/index')
                }
              }
            })
          }
        })
      },
      switchTab(e) {
        if (e === 0) {
          uni.switchTab({
            url: '/pages/index/main'
          })
        } else if (e === 1) {
          uni.switchTab({
            url: '/pages/own/main'
          })
        }
      },
      // 长按删除会话
      longTimePress(item) {
        this.conversation = item
        this.handleModalShow()
      },
      handleModalShow() {
        this.modalVisible = !this.modalVisible
      },
      handleConfirm() {
        this.handleModalShow()
        this.deleteConversation(this.conversation)
      },
      // 将某会话设为已读
      setMessageRead(item) {
        if (item.unreadCount === 0) {
          return
        }
        uni.$app.setMessageRead({
          conversationID: item.conversationID
        })
      },
      // 点击某会话
      checkoutConversation(item, name) {
        name = name.split(',')[0]
        wx.navigateTo({ url: `/pages/chat/main?toAccount=${name}&type=C2C` })
        // this.$store.dispatch('checkoutConversation', item.conversationID)
      },
      
      // 点击系统通知时，处理notification
      checkoutNotification(item) {
        this.$store.commit('resetCurrentConversation')
        this.$store.commit('resetGroup')
        this.setMessageRead(item)
        uni.$app.getConversationProfile(item.conversationID)
          .then((res) => {
            this.$store.commit('updateCurrentConversation', res.data.conversation)
            this.$store.dispatch('getMessageList')
          })
        let url = '../system/main'
        wx.navigateTo({
          url
        })
      },
      // 删除会话
      deleteConversation(item) {
        uni.$app.deleteConversation(item.conversationID).then((res) => {
          console.log('delete success', res)
        })
      },
      empty() {
        let url = '../search/main?type=user'
        uni.navigateTo({
          url
        })
      }
    },
    onLoad() {
      // #ifdef APP-PLUS
      plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
        this.version = wgtinfo.version
        this.checkVersion()
      })
      //#endif
      // if (!this.isSdkReady) {
      // 	uni.showLoading({
      // 		title: '正在同步数据',
      // 		mask: true
      // 	})
      // }
    },
    watch: {
      isSdkReady(newVal) {
        if (newVal) {
          uni.hideLoading()
        }
      }
    }
  }
</script>

<style lang='scss'>
  .chat-container {
    background-color: $background;
    min-height: 100vh;
    box-sizing: border-box;
    border-bottom: 1px solid $border-base;

    .chat {
      background-color: #FFFFFF;
      box-sizing: border-box;
      display: flex;
      height: 72px;

      &:last-child .right {
        border-bottom: none;
      }

      .avatar-container {
        padding: 12px;
        box-sizing: border-box;

        .avatar {
          border-radius: 4px;
          height: 48px;
          width: 48px;
        }
      }
    }
  }

  .information {
    display: flex;
    flex-direction: column;
    padding-right: 10px;
    height: 48px;
    width: 60%;
    flex-grow: 1;

    .username {
      color: $base;
      font-size: 18px;
      line-height: 28px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .content {
      color: $secondary;
      font-size: 14px;
      overflow: hidden;
      line-height: 20px;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .right {
    padding: 12px 0;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    border-bottom: 1px solid $light-background;
    width: calc(100% - 80px); // 80px 是头像框的宽度
    flex-grow: 1;
  }

  .time {
    padding-right: 16px;
    display: flex;
    flex-direction: column;
    flex-basis: 100px;
    text-align: right;

    .last {
      color: $secondary;
      font-size: 12px;
      line-height: 28px;

      .remain {
        display: flex;
        flex-direction: row-reverse;

        .info {
          color: #FFFFFF;
          font-size: 12px;
          background-color: $danger;
          border-radius: 30px;
          padding: 2px 7px 3px;
        }
      }
    }
  }

  .empty {
    display: flex;
    align-content: center;
    justify-content: center;
    height: 800rpx;
    .empty-button {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 46px;
      color: #FFFFFF;
      margin-top: 40vh;
      padding: 12px;
      background-color: $primary;
      border-radius: 6px;
      font-size: 18px;
      width: 80vw;

      &:before {
        content: '+';
        font-size: 22px;
        margin-right: 12px;
      }
    }
  }

  .input {
    text-align: center;
    height: 32px;
    background-color: #FFFFFF;
    border-radius: 8px;
    font-size: 16px;
  }

  .content-red {
    color: $danger;
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 80%;
  }

  .delete {
    color: #FFFFFF;
    font-size: 14px;
    font-weight: 600;
    background-color: $danger;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .delete-button {
    text-align: center;
  }
</style>
